package com.itxzh.logindemo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.itxzh.logindemo.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Description
 *
 * @Author ldt
 * @Date 2022/5/31 10:44
 * @Version 1.0.0
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        Map<String, Object> ret = new HashMap<>();
        try {
            JwtUtil.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("status", "-1");
            ret.put("msg", e.getMessage());
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSONObject.toJSONString(ret));
        return false;
    }
}
